<?php
class TraineesController extends AppController {

	var $name = 'Trainees';
	var $helpers = array('Javascript','Ajax');
	var $components = array('RequestHandler', 'Captcha', 'Email', 'Util');
	// var $components = array('RequestHandler', 'Email', 'Util');
	function admin_index() {
		$this->Trainee->recursive = 0;
		$this->set('trainees', $this->paginate());
	}

	function admin_view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid trainee', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('trainee', $this->Trainee->read(null, $id));
	}
	function captcha_image() 
    { 
		// Configure::write( 'debug', 0 );
        $this->Captcha->image(); 
        $this->autoRender = false;
		// $this->render();
    } 
    
	//ThanhBC: xu ly phan dang nhap
	function login()
	{
		$this->layout = 'testcenter';
		if (!empty($this->data))		//lay du lieu tu form login
		{
			$loginfail = 0;
			if($this->Session->check('loginfail'))
			{
				$loginfail = $this->Session->read('loginfail');
				if($loginfail > 2)
				{
					$captcha = $this->data['Trainee']['captcha'];
				}
			}
			if($loginfail > 2 && !$this->Captcha->check($captcha))
			{
				$error = "Captcha is wrong";
				$this->set("error",$error);
//                                $this->data['Trainee']['captcha'] = '';
				//$this->redirect(array('controller'=>'Trainees', 'action'=>'login'));
			}
			else
			{
				$results = $this->Trainee->findByUser($this->data['Trainee']['user']);

				if ($results && $results['Trainee']['pass'] == md5($this->data['Trainee']['pass']) && $results['Trainee']['status'] == 1)
				{
						// $this->Session->setFlash('Xin chao ban');
						//flush into a session
						$this->Session->write('user', $this->data['Trainee']['user']);
						$this->Session->write('loginfail', 0);
						$this->redirect(array('controller'=>'Trainees', 'action'=>'step1'));					
				}
				else
				{
						$this->Session->write('loginfail', ($loginfail + 1));
						$error = 'User or password is incorrect! Please try again!';
						$this->set("errorlogin",$error);                                   
//                                    $this->redirect('/');
				}
			}   
		}
		// $this->set("error",$error);
		// $this->render("/trainees/login"); 		
	}
	function logout()
	{
		if ($this->Session->check('user'))
		{
			$this->Session->destroy();
			$this->redirect('/');
		}
	}
	
	function myencrypt($first)
	{
		return md5($first);
	}
	
	function register()
	{
		$error = "Loi dang ky";
		$this->layout = 'testcenter';	
		$webroot_path = $this->webroot;		
		//ThanhBC: change
		//if(isset($_POST['ok']))
		//{			
			if (!empty($this->data))
			{
				$this->Trainee->create();				
				//$birthday = ($this->data['Trainee']['yob'] + 1900) .'-'. ($this->data['Trainee']['mob'] + 1).'-'. ($this->data['Trainee']['dob'] + 1);
			//pr("birthday: " . $birthday);
				$encrypt_pass	= md5($this->data['Trainee']['pass']);
				$activationCode = sha1(mt_rand(10000,99999).time().$this->data['Trainee']['user']);
				$this->Session->write('activation_code', $activationCode);
				$this->Session->write('inactive_user', $this->data['Trainee']['user']);
				$this->Trainee->set(array(
									'user' => $this->data['Trainee']['user'],
									'pass' => $encrypt_pass,
									'title' => $this->data['Trainee']['title'],
									'gender' => $this->data['Trainee']['gender'],
									'firstname' => $this->data['Trainee']['firstname'],
									'middlename' => $this->data['Trainee']['middlename'],
									'lastname' => $this->data['Trainee']['lastname'],
									'email' => $this->data['Trainee']['email'],
									//'birthday' => $birthday,
									'addtyp' => $this->data['Trainee']['addtyp'],
									'address' => $this->data['Trainee']['address'],
									'country_id' => $this->data['Trainee']['country_id'],
									'city_id' => $this->data['Trainee']['city_id'],
									//2013-02-25 Pham Vien: fixed bug: Frontpage_Register_EF.docx - 1.
									// 'pincode' => $this->data['Trainee']['pincode'],
									'phonetyp' => $this->data['Trainee']['phonetyp'],
									'phone' => $this->data['Trainee']['phone'],
									//'fax' => $this->data['Trainee']['fax'],
									//'im' => $this->data['Trainee']['im'],
									//2013-02-25 Pham Vien: fixed bug: Frontpage_Register_EF.docx - 1.
									// 'idcard' => $this->data['Trainee']['idcard'],
									'status' => 0,
									'datecreated' => date("d/m/y : H:i:s", time()),
									'datelastmaint' => date("d/m/y : H:i:s", time()),
									'condition' => $this->data['Trainee']['condition'],
									'activation_code' => $activationCode
									));
									
				if ($this->Trainee->save())
				{
					$this->Session->setFlash('Luu thanh cong!');
//					$this->Session->write('user', $this->data['Trainee']['user']);
					// $this->redirect(array('controller'=>'Trainees', 'action'=>'useracount'));
					$this->redirect(array('controller'=>'Trainees', 'action'=>'regresult'));
				}
				else
				{
					$this->Session->setFlash('Co loi trong viec luu du lieu!');
				}
			}			
			$countries = $this->Trainee->Country->find('list', array('fields'=>'Country.name'));
			//Lay danh sach city default
			// $cities = array();
			$cities = $this->Trainee->City->find('list', array('City.country_id' => 1, 'fields' => 'City.name'));

			$this->set(compact('countries', 'cities'));			
			$this->set("error", $error);
			// pr($this->validationErrors());
			// pr($this->Trainee->invalidFields());
        
	}
	#Sau nay them doan kiem tra user do da kich hoat chua qua mail, neu chua thi moi kich hoat
	function regresult()
	{
		$this->layout = 'testcenter';
		$user = $this->Session->read('inactive_user');
		$trainees = $this->Trainee->findByUser($user);
//print_r(stream_get_transports());
		$email1 = array('to' => $trainees['Trainee']['email'], 'subject' => 'Activation request for register.edufirst.vn', 'content' => 'Noi dung chinh nam o day!');
		try
		{
			$this->sendMail($email1);
		}
		catch  (Exception  $e)  
		{ 
			pr("Loi: $e");
		}
	}
	//ThanhBC: lost password form
	function recover()
	{
		$this->layout = 'testcenter';
		if (!empty($this->data))
		{
			$msg = "";
			$newActivationCode = sha1(mt_rand(10000,99999).time() . $this->data['Trainee']['txtemail']);
			$info = array(	'to' => $this->data['Trainee']['txtemail'],
							'subject' => $this->Util->getMessage('SUBJECT_EMAIL_RESETPW'),
							'template' => 'reset_password',
							'key' => $newActivationCode
						);
			$this->Trainee->query('call updateactivationcode_prc(\'' . $this->data['Trainee']['txtemail'] . '\',\'' . $newActivationCode .'\', @result);');
			$resultset = $this->Trainee->query("SELECT @result");
			$result = $resultset[0][0]['@result'];
			if($result == 1)
			{
				//send mail yeu cau reset password
				$this->sendResetPasswordAlert($info);
			}
			$this->redirect(array('action'=>'recoverresult', $result));
		}
		// $webroot_path = $this->webroot;
		// $this->set('aaa', $webroot_path);
	}
	function recoverresult($r=null)
	{
		$this->layout = 'testcenter';
		$this->set('result', $r);
	}
	function get_cities_ajax()
	{
		if($this->RequestHandler->isAjax())
		{
			$this->set('cities', $this->Trainee->City->find('list',
                           array('conditions' =>
                                       array('City.country_id' => $this->params['url']['countryId']),
                                       // array('City.country_id' => $_POST['countryId']),
                                 'recursive' => -1)));
		}
	}

	function admin_edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid trainee', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Trainee->save($this->data)) {
				$this->Session->setFlash(__('The trainee has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The trainee could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Trainee->read(null, $id);
		}
	}

	function admin_delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for trainee', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Trainee->delete($id)) {
			$this->Session->setFlash(__('Trainee deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Trainee was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
	
	//ThanhBC: if success login
	function useracount()
	{
		if ($this->Session->check('user'))
		{
		//	echo "test test";
			//exit;
			$this->layout = 'useracount';	
			$user = $this->Session->read('user');
			$trainee = $this->Trainee->findByUser($user);
			$this->set('trainee', $trainee);
			//$this->set('user', $user);
		}
		else
		{
			$this->redirect('/');
		}
	}
	function get_timeslot($venueID, $year, $month, $date)
	{
		$this->loadModel('Testslot');
		$this->loadModel('Venue');
		$venue = $this->Venue->read(null, $venueID);
        $maxSlot = $venue['Venue']['pc'];
		$query = "select t.id, t.description from timeslots t
where t.id not in (select ts.timeslot_id from testslots ts where ts.venue_id=$venueID and ts.amount>=$maxSlot and ts.date=date('$year-$month-$date'))";
		$arr = $this->Testslot->query($query);
		return $arr;
	}
	function get_timeslot_ajax()
	{
		if($this->RequestHandler->isAjax())
		{			
			$venueID = $_POST['loc'];
			
			$date = $_POST['date'];
			$month = $_POST['month'];
			$year = $_POST['year'];
			$arr = $this->get_timeslot($venueID, $year, $month, $date);

			$this->set('timeslots', $arr);
		}
	}
	function editsubject ($id = null)
	{
		$result = 0;//mac dinh update testslot that bai
		$this->layout = 'step_layout';		
		// pr("id: ".$id);
		$this->loadModel('Receipt');
		$this->loadModel('Timeslot');
		$this->loadModel('Testsite');		
		$receipt = $this->Receipt->read(null, $id);
		$venue = $receipt['Testslot']['venue_id'];
		$user = $this->Session->read('user');
		//$testslot = $receipt->
		//Kiem tra co phai receipt cua user do khong
		if($receipt['Trainee']['user'] != $user)
		{
			$this->Session->setFlash(__('Invalid subject', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!$id && empty($this->data)) 
		{
			$this->Session->setFlash(__('Invalid subject', true));
			$this->redirect(array('action' => 'index'));
		}
		if(!empty($this->data)) {
			$timeslot = $this->data['Trainee']['timeslot'];
			if($timeslot == null)
			{
				$this->set('update_error_msg_timeslot', $this->Util->getMessage('INVALID_TIME_SLOT'));
			}
			else
			{
				$this->set('update_error_msg_timeslot', '');
				$date = $this->data['Trainee']['yearTest']."-".$this->data['Trainee']['monthTest']."-".$this->data['Trainee']['dayTest'];
				$this->Trainee->query('call update_testslot_prc(' . $id . ',' . $timeslot . ',' . $venue . ',\'' . $date . '\', @result);');
				//kiem tra ket qua tra ve ngay test co hop le hay khong
				$resultset = $this->Trainee->query("SELECT @result");
				// pr($resultset);
				$result = $resultset[0][0]['@result'];
				if($result == 1)
				{
					$this->redirect(array('action' => 'curact'));
				}
				else if($result == 2)
				{
					$this->set('update_error_msg', $this->Util->getMessage('FULL_SLOT_ERROR'));
				}
				else
				{
					$this->set('update_error_msg', $this->Util->getMessage('INVALID_TEST_DATE'));
				}
			}
		}
		$datetime = strtotime($receipt['Testslot']['date']);
		$edittedDate = date('d', $datetime);
		$edittedMonth = date('n', $datetime);
		$edittedYear = date('Y', $datetime);
		$edittedTimeslot = $receipt['Testslot']['timeslot_id'];
		// $timeslots = $this->Timeslot->find('list', array('recursive' => -1));
		$timeslots = $this->get_timeslot($venue, $edittedYear, $edittedMonth, $edittedDate);
		//lay testsite
		$testSite = $this->Testsite->query('select c.testsite_id from receipts r, subjects s, categories c where r.subject_id=s.id and s.category_id=c.id and r.id=' . $id);		
		$testSiteID = $testSite[0]['c']['testsite_id'];
		$this->set(compact('edittedDate', 'edittedMonth', 'edittedYear', 'edittedTimeslot', 'timeslots', 'id', 'testSiteID', 'venue'));
		$this->data['Trainee']['id'] = $id;		
		// $this->set(compact('receipt'));

	}
	function saveeditsubject ()
	{
		if (!empty($this->data)) {
			if ($this->Subject->save($this->data)) {
				$this->Session->setFlash(__('The subject has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The subject could not be saved. Please, try again.', true));
			}
		}
	}
	
	function update_info()
	{
		if ($this->Session->check('user'))
		{
			$this->layout = 'useracount';	
			$user = $this->Session->read('user');
			
			if ($this->Trainee->save($this->data, array('Trainee.user'=>$user)))
			{
				$this->Session->setFlash('Luu thanh cong!');
				//$this->Session->write('user', $this->data['Trainee']['user']);
				$this->redirect(array('controller'=>'Trainees', 'action'=>'useracount'));
			}
			else
			{
				$this->Session->setFlash('Co loi trong viec luu du lieu!');
			}
				
			$countries = $this->Trainee->Country->find('list', array('fields'=>'Country.name'));
			//Lay danh sach city default
			// $cities = array();
			$cities = $this->Trainee->City->find('list', array('City.country_id' => 1, 'fields' => 'City.name'));

			$this->set(compact('countries', 'cities'));			
			//$this->set("error", $error);
			if (empty($this->data)) {
				$trainee = $this->Trainee->findByUser($user);
				 $this->data = $trainee;
				//$this->data['
			}
		}
		else
		{
			$this->redirect('/');
		}
	}
	
	//ThanhBC: step
	function step1()
	{
		if ($this->Session->check('user'))
		{
			$this->layout = 'step_layout';	
			$user = $this->Session->read('user');
			$trainee = $this->Trainee->findByUser($user);
			$this->set('trainee', $trainee);
			
			//dua vao combobox
			$this->loadModel('Category');	//ThanhBC: load another model
			$this->loadModel('Subject');	//ThanhBC: load another model
			$this->loadModel('Testsite');	//ThanhBC: load another model
			$categories = $this->Category->find('list', array('field'=>'Category.name'));
			//$programs = array();		//ThanhBC: de null de sau nay load ajax len
			$programs = $this->Subject->find('list', array('field'=>'Subject.name'));
			$testsites = $this->Testsite->find('list', array('field'=>'Testsite.name'));
			$this->set(compact('categories', 'programs', 'testsites'));	
		
		}
		else
		{
			$this->redirect('/');
		}
	}
	function get_categories_ajax()
	{
		if($this->RequestHandler->isAjax())
		{
			$this->loadModel('Category');
			$this->set('categories', $this->Category->find('list',
                           array('conditions' =>
                                       array('Category.testsite_id' => $this->params['url']['testsiteId']),
                                       // array('City.country_id' => $_POST['countryId']),
                                 'recursive' => -1)));
		}
	}
	function get_subjects_ajax()
	{
		if($this->RequestHandler->isAjax())
		{

			$this->loadModel('Subject');

			$arr = $this->Subject->find('all',
                           array('conditions' =>
                                       array('Subject.category_id' => $this->params['url']['categoryId']),
                                       // array('City.country_id' => $_POST['countryId']),
                                 'recursive' => -1, 'fields'=>array('Subject.id', 'Subject.name', 'Subject.code', 'Subject.cost')));

			// $sql = "Select id, name, code, FORMAT(cost, 0) cost From Subjects t where t.category_id = " . $this->params['url']['categoryId'];
			// $arr = $this->Subject->query($sql);

			$this->set('subjects', $arr);
		}
	}
   
	function savestep1()
	{
		//ThanhBC: save in session
		if(!empty($this->data['subjectID']))
		{
			$this->Session->write('testsiteID', $this->data['Trainee']['testsites']);
			// $this->Session->write('testID', $this->data['Trainee']['testID']);
			//$this->Session->write('catID', $this->data['Trainee']['cat']);
			//$this->Session->write('programID', $this->data['Trainee']['program']);
			$this->Session->write('programID', $this->data['subjectID']);
			
			$this->redirect(array('controller'=>'trainees', 'action'=>'step2'));
		}
		else
		{
			$this->redirect(array('controller'=>'trainees', 'action'=>'step1'));
		}
	}
	function checkTestTime($testSiteID, $date, $month, $year)
	{
		$query = "select datediff(ifnull(date('". $year . "-" . $month . "-" . $date ."'), date('2000-01-01')),sysdate()) as datediff";
		$validation = $this->Trainee->query($query);
		$datediff = $validation[0][0]['datediff'];
		
		$query = "select count(*)-1 as wdatediff from calendars t where t.date <= ifnull(date('". $year . "-" . $month . "-" . $date ."'), date('2000-01-01')) and t.date >= sysdate() and t.holiday=0";
		$validation1 = $this->Trainee->query($query);
		$wdatediff = $validation1[0][0]['wdatediff'];
		$minVue = $this->Util->getParameter('MIN_VUE');
		$maxVue = $this->Util->getParameter('MAX_VUE');
		$minPro = $this->Util->getParameter('MIN_PRO');
		$maxPro = $this->Util->getParameter('MAX_PRO');
		if($testSiteID == 1)//VUE
		{
			if($wdatediff < $minVue || $datediff > $maxVue)
				return false;
		}
		else if($testSiteID ==2)//Prometric
		{
			if($wdatediff < $minPro || $datediff > $maxPro)
				return false;
		}
		return true;
	}
	function check_test_time_ajax()
	{
		if($this->RequestHandler->isAjax())
		{
		
			$date = $_POST['date'];
			$month = $_POST['month'];
			$year = $_POST['year'];
			
			if(isset($_POST['testsite']))
			{
				$testSiteID = $_POST['testsite'];
			}
			else
			{
				$testSiteID = $this->Session->read('testsiteID');
			}
			if(!$this->checkTestTime($testSiteID, $date, $month, $year))
			{
				echo $this->Util->getMessage('INVALID_TEST_DATE');				
			}
			$this->autoRender = false;			
		}
	}
	function checkVoucherExp()
	{
		if($this->RequestHandler->isAjax())
		{
			$date = $_POST['date'];
			$month = $_POST['month'];
			$year = $_POST['year'];
			$query = "select datediff(ifnull(date('". $year . "-" . $month . "-" . $date ."'), date('2000-01-01')),sysdate()) as datediff";
			$validation = $this->Trainee->query($query);
			$datediff = $validation[0][0]['datediff'];
			if($datediff < 0)
			{
				echo "Exp date is invalid";
			}
			$this->autoRender = false;
		}
	}
	function step2()
	{
		if ($this->Session->check('user'))
		{
			$this->layout = 'step_layout';	
			
			$this->loadModel('Venue');
			$venues = $this->Venue->find('list', array('fields'=>array('Venue.id', 'Venue.addr')));
			$this->set(compact('venues'));
			
			// $this->loadModel('Timeslot');
			// $timeslots = $this->Timeslot->find('list', array('fields'=>array('Timeslot.id', 'Timeslot.description')));
			// $this->set(compact('timeslots'));
			
		}
		else
		{
			$this->redirect('/');
		}
	}
	function get_exp_timeslot()
	{
	
	}
	function savestep2()
	{
		$date = $this->data['Trainee']['dayTest'];
		$month = $this->data['Trainee']['monthTest'];
		$year = $this->data['Trainee']['yearTest'];
		$testSiteID = $this->Session->read('testsiteID');
		if(!$this->checkTestTime($testSiteID, $date, $month, $year) || empty($this->data['Trainee']['duration']))
		{
			// $this->Session->write('st2_errormsg', "<span style='font-size:11px; font-family: Tahoma; color:#FF0000'>Test time is invalid</span>");
			// $this->set('st2_errormsg', "<span style=\'font-size:11px; font-family: Tahoma; color:#FF0000\'>Test time is invalid</span>");
			// $this->set('st2_errormsg', "Test time is invalid");
			$this->redirect(array('controller'=>'trainees', 'action'=>'step2'));
			// $this->layout = 'step_layout';	
			// $this->render("step2");
		}
		else
		{
		$this->Session->write('testwhere', $this->data['Trainee']['testwhere']);		
		//for use later
		//$this->Session->write('scheduleID', '9999999');
		//$this->Session->write('testTime', $this->data['Trainee']['Testtime']);
		$this->Session->write('yearTest', $year);
		$this->Session->write('monthTest', $month);
		$this->Session->write('dayTest', $date);
		
		$this->Session->write('testTime', $this->data['Trainee']['yearTest']."-".$this->data['Trainee']['monthTest']."-".$this->data['Trainee']['dayTest']);
		
		$this->Session->write('duration', $this->data['Trainee']['duration']);
		//voucher_no
		$this->Session->write('v_no', $this->data['Trainee']['voucher_no']);
		//voucher_exp
		$this->Session->write('yearExp', $this->data['Trainee']['yearExp']);
		$this->Session->write('monthExp', $this->data['Trainee']['monthExp']);
		$this->Session->write('dayExp', $this->data['Trainee']['dayExp']);
		
		$this->Session->write('v_exp', $this->data['Trainee']['yearExp']."-".$this->data['Trainee']['monthExp']."-".$this->data['Trainee']['dayExp']);
				
		$this->redirect(array('controller'=>'trainees', 'action'=>'step3'));
		}
	}
	
	function step3()
	{
		if ($this->Session->check('user'))
		{
			$this->layout = 'step_layout';				
									
			//for print out
			$user = $this->Session->read('user');
			$trainee = $this->Trainee->findByUser($user);				
			$this->set('trainee', $trainee);
			
			// $testtime = $this->Session->read('monthTest')."-".$this->Session->read('dayTest')."-".$this->Session->read('yearTest');
			// $this->set('testtime', $testtime);
			$this->set('testTime', $this->Session->read('testTime'));
			$this->loadModel('Timeslot');
			$timeslots = $this->Timeslot->read(null, $this->Session->read('duration'));
			$this->set('timeslots', $timeslots["Timeslot"]["description"]);
			$this->set('v_no', $this->Session->read('v_no'));
			$this->set('v_exp', $this->Session->read('v_exp'));
			
			$this->loadModel('Testsite');
			$testsite = $this->Testsite->read(null, $this->Session->read('testsiteID'));//find($this->Session->read('testsiteID'));
			$this->set('testsite', $testsite['Testsite']['name']);
			
			$this->set('testID', $this->Session->read('testID'));
			
			$this->loadModel('Category');
			$category = $this->Category->read(null, $this->Session->read('catID'));
			$this->set('cat', $category['Category']['name']);
			
			$this->loadModel('Subject');
			$program = $this->Subject->read(null, $this->Session->read('programID'));
			$this->set('program', $program);
			
			$this->loadModel('Venue');
			$testlocation = $this->Venue->read(null, $this->Session->read('testwhere'));
			$this->set('testlocation', $testlocation['Venue']['addr']);
		}
		else
		{
			$this->redirect('/');
		}
	}
	
	function step4()
	{
		if ($this->Session->check('user'))
		{
			$this->layout = 'step_layout';
		}
		else
		{
			$this->redirect('/');
		}
	}
	
	function savestep4()
	{
		//var $paymethod = 0;
		//echo "gia tri cua checkbox 1  ".$this->data['Trainee']['switchBox3'];
		$next = false;
		if ($this->data['Trainee']['switchBox3'] == "1")
		{
			$paymethod = 1;//'EF';
			$next = true;
		}
		elseif ($this->data['Trainee']['switchBox4'] == "1")
		{
			$paymethod = 2;//'BT';
			$next = true;
		}
		elseif ($this->data['Trainee']['switchBox5'] == "1")
		{
			$paymethod = 3;//NL
			$next = true;
		}
		// elseif ($this->data['Trainee']['switchBox6'] == "1")
		// {
			// $paymethod = 'NL';
			// $next = true;
		// }
		if($next)
		{
			$this->Session->write('paymentID', $paymethod);
			//echo "kieu thanh toan - kieu thanh toan ".$this->Session->read('paymentID');
			//exit;
			$this->redirect(array('controller'=>'trainees', 'action'=>'step5'));
		}
		else
		{
			$this->redirect(array('controller'=>'trainees', 'action'=>'step4'));
		}
	}
	
	function step5()
	{
		if ($this->Session->check('user'))
		{
			$this->layout = 'step_layout';
			
            //for print out
			$user = $this->Session->read('user');
			$trainee = $this->Trainee->findByUser($user);				
			$this->set('trainee', $trainee);
			
			$this->set('testTime', $this->Session->read('testTime'));
			$this->set('v_no', $this->Session->read('v_no'));
			$this->set('v_exp', $this->Session->read('v_exp'));
			
			$this->loadModel('Testsite');
			$testsite = $this->Testsite->read(null, $this->Session->read('testsiteID'));//find($this->Session->read('testsiteID'));
			$this->set('testsite', $testsite['Testsite']['name']);
			
			$this->set('testID', $this->Session->read('testID'));
			
			$this->loadModel('Category');
			$category = $this->Category->read(null, $this->Session->read('catID'));
			$this->set('cat', $category['Category']['name']);
			
			$this->loadModel('Subject');
			$program = $this->Subject->read(null, $this->Session->read('programID'));
			$this->set('program', $program);
			
			$this->loadModel('Venue');
			$testlocation = $this->Venue->read(null, $this->Session->read('testwhere'));
			$this->set('testlocation', $testlocation['Venue']['addr']);			
			$this->set('typePay', $this->Session->read('paymentID'));
			
			$this->loadModel('Timeslot');
			$timeslots = $this->Timeslot->read(null, $this->Session->read('duration'));
			// $this->Session->write('timeslot_id', $timeslots["Timeslot"]["id"]);
			$this->set('timeslot_desc', $timeslots["Timeslot"]["description"]);
          
		}
		else
		{
			$this->redirect('/');
		}
	}
	function savestep5() 
	{
		$user = $this->Session->read('user');
		$trainee = $this->Trainee->findByUser($user);
		$venue_id = $this->Session->read('testwhere');
		$testdate = $this->Session->read('testTime');
		$timeslot_id = $this->Session->read('duration');
		$payment_id = $this->Session->read('paymentID');
		$promotion_code = $this->Session->read('v_no');
		$promotion_exp = $this->Session->read('v_exp');
		$this->loadModel('Subject');
		$subject = $this->Subject->findById($this->Session->read('programID'));
		$testSiteID = $this->Session->read('testsiteID');
		$this->Trainee->query('call addreceipt_prc(' . $testSiteID .',' . $trainee['Trainee']['id'] . ',' . $this->Session->read('programID') . ','. $subject['Subject']['cost'] . ',' . $venue_id . ',\''. $testdate . '\',' . $timeslot_id . ','. $payment_id . ',\'' . $promotion_code .'\', \'' . $promotion_exp . '\', @result);');
		$resultset = $this->Trainee->query("SELECT @result");
		$result = $resultset[0][0]['@result'];
		//Neu dang ky thi thanh cong
		if($result > 0)
		{
			//Xoa cac bien session
			$this->Session->delete('testwhere');
			$this->Session->delete('testTime');
			$this->Session->delete('duration');
			$this->Session->delete('duration');
			$this->Session->delete('paymentID');
			$this->Session->delete('v_no');
			$this->Session->delete('v_exp');
			$this->Session->delete('testsiteID');
			$this->Session->delete('programID');
			$this->Session->delete('dayExp');
			$this->Session->delete('monthExp');
			$this->Session->delete('yearExp');
			$this->Session->delete('dayTest');
			$this->Session->delete('monthTest');
			$this->Session->delete('yearTest');
		}
		if($result > 0 && $payment_id == 3)//nganluong.vn
		{
			App::import('Vendor', 'nganluong');
		
			//Khoi tao doi tuong checkout
			$NL_Checkout = New NL_Checkout;
			
			//Khai bao bien de tao checkout url
			
			//khai bao bien return url sau khi xu ly xong thanh toan
			$return_url = $_SERVER['HTTP_HOST'] ."/trainees/thank";
			// echo "URL: " . $return_url;
			
			//khai bao nguoi nhan tien
			$receiver = "phamvien@gmail.com";
			
			//transacton ve don hang
			// $transaction_info = "Ban hang trong ngay";
			
			$this->loadModel('Subject');
			//khai bao bien order code ma don hang
			$program = $this->Subject->read(null, $this->Session->read('programID'));
			
			$order_code = $program['Subject']['code'];
			$transaction_info = $order_code;
			
			//Tong gia tri thanh toan
			$price =  $program['Subject']['cost'];
			
			//buicheckout
			$checkout_url = $NL_Checkout->buildCheckoutURL($return_url, $receiver, $transaction_info, $order_code, $price);
			//$this->set('checkout_url', $checkout_url);
			$this->redirect($checkout_url);
		   //end nganluong			
		}
		else
		{
			$this->redirect(array('action'=>'result', $result));
		}
	}
	function savestep51() {
		//if (!empty($this->data)) {
	   $this->loadModel('Trainee');
	   $user = $this->Session->read('user');
       $trainee = $this->Trainee->findByUser($user);
		date_default_timezone_set('Asia/Ho_Chi_Minh');	   
		$currDate = date('Y-m-d H:i:s');	
		
		//lay gia tri id cua schedule
        $amount = 0;
        $this->loadModel('Testslot');
        $testslot = $this->Testslot->find('first', array('conditions'=>array(
																				'venue_id'=>$this->Session->read('testwhere'),
																				'date'=>$this->Session->read('testTime'),
																				'timeslot_id'=>$this->Session->read('timeslot_id')
																			)
														)
										 );		
		
		// print_r($schedule);
		// exit;
		// echo "cac gia tri:"; echo "<br>";
		// echo "venue_id:".$this->Session->read('testwhere');echo "<br>";
		// echo "subject_id:".$this->Session->read('programID');echo "<br>";
		// echo "date:".$this->Session->read('testTime');echo "<br>";
		// echo "timeslot_id:".$this->Session->read('duration');
		// exit;
        if ($testslot == null)  //chua co lich nay -> them moi
        {
			$this->Testslot->create();
            $this->Testslot->set(array(	'venue_id'=>$this->Session->read('testwhere'),										
										'date'=>$this->Session->read('testTime'),
										'timeslot_id'=>$this->Session->read('timeslot_id'),
                                                                                'amount'=>0)
								);
			$this->Testslot->save();	
			$tid = $this->Testslot->getLastInsertId();
			// echo "id moi la: ".$sid;
        }
        else
        {
			$venue_id = $this->Session->read('testwhere');
			$this->loadModel('Venue');
			$venue = $this->Venue->read(null, $venue_id);
			$pc = $venue['Venue']['pc'];
			if($testslot['Testslot']['amount'] >= $pc)
			{
				$this->redirect(array('action'=>'result', 0));
			}
            $tid = $testslot['Testslot']['id'];
            $amount = $testslot['Testslot']['amount'];
        }
        //Kiem tra schedule ton tai chua
		/*
        $this->loadModel('Schedule');
        $schedule = $this->Schedule->find('first', array('conditions'=>array(
                                                                            'testslot_id'=>$tid,
                                                                            'subject_id'=>$this->Session->read('programID')
                                                                            )
                                                        )
					);
        if($schedule == null)
        {
            $this->Schedule->create();
            $this->Schedule->set(array(	'testslot_id'=>$tid,										
                                        'date'=>$this->Session->read('testTime'),
                                        'subject_id'=>$this->Session->read('programID'))
								);
            $this->Schedule->save();	
            $sid = $this->Schedule->getLastInsertId();            
        }
        else
        {
            $sid = $schedule['Schedule']['id'];
        }
        */        
		$this->loadModel('Receipt');
		$this->loadModel('Subject');
		$subject = $this->Subject->findById($this->Session->read('programID'));
		$this->Receipt->create();
        $this->Receipt->set(array(
								'trainee_id' => $trainee['Trainee']['id'],
								'subject_id' => $this->Session->read('programID'),
								'testslot_id' => $tid,
								'payment_id' => $this->Session->read('paymentID'),
								'datecreated' => $currDate,
								'transaction_id' => 0,
								'amount' => $subject['Subject']['cost'],
								'promotion_id' => $this->Session->read('v_no')
							));
		if ($this->Receipt->save($this->data)) {
			$this->Testslot->id = $tid;                        
			$this->Testslot->saveField('amount', $amount + 1);
			//Neu thanh toan qua ngan luong
			if($this->Session->read('paymentID') == 'NL')
			{
				App::import('Vendor', 'nganluong');
			
				//Khoi tao doi tuong checkout
				$NL_Checkout = New NL_Checkout;
				
				//Khai bao bien de tao checkout url
				
				//khai bao bien return url sau khi xu ly xong thanh toan
				$return_url = $_SERVER['HTTP_HOST'] ."/trainees/thank";
				// echo "URL: " . $return_url;
				
				//khai bao nguoi nhan tien
				$receiver = "phamvien@gmail.com";
				
				//transacton ve don hang
				// $transaction_info = "Ban hang trong ngay";
				
				$this->loadModel('Subject');
				//khai bao bien order code ma don hang
				$program = $this->Subject->read(null, $this->Session->read('programID'));
				
				$order_code = $program['Subject']['code'];
				$transaction_info = $order_code;
				
				//Tong gia tri thanh toan
				$price =  $program['Subject']['cost'];
				
				//buicheckout
				$checkout_url = $NL_Checkout->buildCheckoutURL($return_url, $receiver, $transaction_info, $order_code, $price);
				//$this->set('checkout_url', $checkout_url);
				$this->redirect($checkout_url);
			   //end nganluong
			}
			else
			{
				// $this->Session->setFlash(__('The receipt has been saved', true));
				// $this->redirect(array('controller'=>'trainees', 'action' => 'curact'));
				//$return_url = $_SERVER['HTTP_HOST'] ."/receipts/result";
				$this->redirect(array('action'=>'result', $this->Receipt->getLastInsertID ()));
			}
		} else {
			$this->Session->setFlash(__('The receipt could not be saved. Please, try again.', true));
		}
	//}
		// $trainees = $this->Receipt->Trainee->find('list');
		// $schedules = $this->Receipt->Schedule->find('list');
		// $pays = $this->Receipt->Payment->find('list');
		// $this->set(compact('trainees', 'schedules', 'pays'));
	}
	    
	function result($r=null)
	{
		$this->layout = 'step_layout';
		if (!$this->Session->check('user'))
		{
			$this->redirect('/');			
		}	
		if($r > 0)
		{
			$msg = $this->Util->getMessage('SUCCESS_TESTING_REGISTER');
			//Goi email thong bao den khach hang
			$this->sendRegistrationAlert($r);			
		}
		else if($r == -1)
		{
			$msg = $this->Util->getMessage('FULL_SLOT_ERROR');
		}
		else //0
		{
			$msg = $this->Util->getMessage('INVALID_TEST_DATE');
		}
		$this->set('msg', $msg);
	}
	function chpwresult($r=null)
	{
		$this->layout = 'useracount';
		if($r == 1)
		{
			$msg = "You have successfully changed your password!";
		}
		else
		{
			$msg = "Change password failed!";
		}
		$this->set(compact('msg'));
	}
	function examfee()
	{

		$this->layout = 'examfee';
		$this->loadModel('Category');
		$categories = $this->Category->find('list');
		$this->set('categories', $categories);

	}
	
	function curact()
	{
		if ($this->Session->check('user'))
		{
			$this->layout = 'curact';
            $user = $this->Session->read('user');
            $trainee = $this->Trainee->findByUser($user);
            
            $this->loadModel('Receipt');
            $receipts = $this->Receipt->findByTraineeId($trainee['Trainee']['id']);
            
			$ketquas = $this->Receipt->find('all',
												array(
													 //'fields'=>array(),
													 'conditions'=>array(	
																			'trainee_id'=>$trainee['Trainee']['id']
																		 ),
													  'recursive'=>2		//ket tat ca cac bang trong db??? => qua' cham
													 )
											  );
											  
			//echo $trainee['Trainee']['id'];
			//print_r($ketquas);
			//exit;
			$this->set('ketquas', $ketquas);
        }
		else
		{	
			$this->redirect('/');			
		}
	}
	
	function viehis()
	{
		if ($this->Session->check('user'))
		{
			$this->layout = 'viehis';
			$user = $this->Session->read('user');
            $trainee = $this->Trainee->findByUser($user);
            
            $this->loadModel('Receipt');
            $receipts = $this->Receipt->findByTraineeId($trainee['Trainee']['id']);
            
			$this->loadModel('Schedule');
			$ketquas = $this->Receipt->find('all',
												array(
													 //'fields'=>array(),
													 'conditions'=>array(	
																			'trainee_id'=>$trainee['Trainee']['id']
																		 ),
													  'recursive'=>2		//ket tat ca cac bang trong db??? => qua' cham
													 )
											  );
											  
			//echo $trainee['Trainee']['id'];
			//print_r($ketquas);
			//exit;
			$this->set('ketquas', $ketquas);
		}
		else
		{
			$this->redirect('/');
		}
	}
    
    function thank()
    {
        //thanh toan xong tro ve action nay
        //include file
       	App::import('Vendor', 'nganluong');
        $NL_Checkout = New NL_Checkout;
        
        //Lay cac thong tin 
        $transaction_info = $_GET['transaction_info'];
        $order_code = $_GET['order_code'];
        $price = $_GET['price'];
        $payment_id = $_GET['payment_id'];
        $payment_type=$_GET['payment_type'];
        $error_code = $_GET['error_code'];
        $secure_code = $_GET['secure_code'];
        
        //Verify payment
        $result = $NL_Checkout->verifyPaymentURL($transaction_info, $order_code, $price, $payment_id, $payment_type, $error_code, $secure_code);
        
        //Kiem tra ket qua tro ve
        if ($result == 'true')
        {
            if ($error_code = '')
                $message = 'Don hang da bi huy';
            else
            {
                $message = 'Don hang xu ly thanh cong';
                $thanhtoan = array();
                $thanhtoan['transaction_info'] = $transaction_info;
                $thanhtoan['order_code'] = $order_code;
                $thanhtoan['payment_id'] = $payment_id;
                $thanhtoan['payment_type'] = $payment_type;
                $thanhtoan['error_code'] = $error_code;
                $thanhtoan['secure_code'] = $secure_code;
                
                $this->set('tt', $thanhtoan);       //for print on view
                $this->Session->write('thanhtoan', $thanhtoan);     //for use write down into db
            }
                
        }
        else
        {
            $message = 'Thong tin da bi thay doi! Don hang khong xu ly thanh cong!';
        }
    }
	
	function changepw()
	{
		$this->layout = 'useracount';
		if(!empty($this->data))
		{
			if($this->data['Trainee']['txtoldpw'] == "")
			{
				$this->set('errormsgoldpw', "<span style='font-size:11px; font-family: Tahoma; color:#FF0000'>Current password cannot be left blank</span>");
				return;
			}
			if($this->data['Trainee']['txtpw'] == "")
			{
				$this->set('errormsgpw', "<span style='font-size:11px; font-family: Tahoma; color:#FF0000'>New password cannot be left blank</span>");
				return;
			}
			else if($this->data['Trainee']['txtpw'] != $this->data['Trainee']['txtpw1'])
			{
				$this->set('errormsg', "<span style='font-size:11px; font-family: Tahoma; color:#FF0000'>Password does not match</span>");
				return;
			}
			$msg = "";
			$oldpw = md5($this->data['Trainee']['txtoldpw']);
			$pw = md5($this->data['Trainee']['txtpw']);
			$this->Trainee->query('call changepassword_prc(\'' . $this->Session->read('user') . '\',\'' . $oldpw .  '\',\'' . $pw .'\', @result);');
			$resultset = $this->Trainee->query("SELECT @result");
			$result = $resultset[0][0]['@result'];
			$this->redirect(array('action'=>'chpwresult', $result));
		}
	}
	
	function successchange()
	{
		$this->layout = 'useracount';
		$oldp = $this->data['Trainee']['old'];
		$newp = $this->data['Trainee']['new'];
		$renewp = $this->data['Trainee']['renew'];
		
		$user = $this->Session->read('user');
		$trainee = $this->Trainee->findByUser($user);
		
		$error_msg = "";
		if (md5($oldp) != $trainee['Trainee']['pass'])
		{
			$error_msg = "Current password is incorrect!";
		}
		else
		{
			if ($newp != $renewp)
				$error_msg = "New password and retyped password are not match!";
			else
			{
				$this->Trainee->set(array(									
									'pass' => md5($newp)
									));	
				$data1 = array('pass' => md5($newp));
				echo $user;
				print_r($data1);
				
				//$data1 la mang de cap nhap
				//mang 2 de chua dieu kien cap nhap
				exit;
				if ($this->Trainee->save($data1, array('Trainee.user'=>$user)))
					$error_msg = "Cap nhap thanh cong";
			}
		}
		$this->set('error_msg', $error_msg);
	}
	function contact()
	{
		$this->layout = 'contact';
		$this->loadModel("Venues");
		$venues = $this->Venues->find('list', array('fields'=>array('Venues.addr')));
		$this->set('venues', $venues);
	}
	function sendMail($data)
	{		
		$this->Email->to = $data['to'];
		$this->Email->subject = $data['subject'];//"Email kich hoat dang ky tai khoan";
		$this->Email->from = 'Admin '.'<'.Configure::read('smtp.username').'>';
		$this->Email->sendAs = 'both';
		$this->Email->template = 'simple_message';
		$this->Email->smtpOptions = array(
			'port' => Configure::read('smtp.port'),
			'timeout' => '30',
			'host' => Configure::read('smtp.host'),
			'username' => Configure::read('smtp.username'),
			'password' => Configure::read('smtp.password')			
		);
		$this->Email->delivery = 'smtp';
		if ($this->Email->send()) {
			return true;
		} 
		else {
			echo $this->Email->smtpError;
		}
	}
	
	//Kich hoat tai khoan cho khach hang
	function activeaccount()
	{
		$msg = '';
		$this->layout = 'testcenter';
		$user = $_GET['u'];
		$key = $_GET['k'];
		$this->Trainee->query('call active_account_prc(\'' . $user . '\',\'' . $key . '\', @result);');
		$resultset = $this->Trainee->query("SELECT @result");
		$result = $resultset[0][0]['@result'];
		if($result == 1)
		{
			$msg = 'Active account successfully!';
		}
		else
		{
			$msg = 'Active account fail!';
		}
		$this->set('msg', $msg);
		$this->set('result', $result);
	}
	
	//Goi email thong bao cho khach hang sau khi dang ky thi thanh cong
	function sendRegistrationAlert($r)
	{
		$user = $this->Session->read('user');
		$trainees = $this->Trainee->findByUser($user);
		$this->loadModel('Receipt');
		$this->loadModel('Timeslot');
		$this->loadModel('Venue');
		$receipt = $this->Receipt->findById($r);
		
	 	$timeslot = $this->Timeslot->findById($receipt['Testslot']['timeslot_id']);
		$venue = $this->Venue->findById($receipt['Testslot']['venue_id']);
		// pr($receipt);
		// pr($timeslot);
		// pr($venue);
		// pr($receipt);
		$this->Email->to = $trainees['Trainee']['email'];
		$this->Email->subject = 'Registration Information for register.edufirst.vn';
		$this->Email->from = 'Admin '.'<'.Configure::read('smtp.username').'>';
		$this->Email->sendAs = 'both';
		$this->Email->template = 'successful_receipt';
		$this->Email->smtpOptions = array(
			'port' => Configure::read('smtp.port'),
			'timeout' => '30',
			'host' => Configure::read('smtp.host'),
			'username' => Configure::read('smtp.username'),
			'password' => Configure::read('smtp.password')			
		);
		$this->set('user', $user);
		$this->set('subject', $receipt['Subject']['name']);
		$this->set('testdate', $receipt['Testslot']['date']);
		$this->set('timeslot', $timeslot['Timeslot']['description']);
		$this->set('venue', $venue['Venue']['addr']);
		$this->set('amount', $receipt['Receipt']['amount']);
		$this->Email->delivery = 'smtp';
		if ($this->Email->send()) {
			CakeLog::write('debug success', "sendRegistrationAlert: $r" . $this->Email->smtpError);
			return true;
		} 
		else {
			CakeLog::write('debug error', "sendRegistrationAlert: $r" . $this->Email->smtpError);
		}
	}
	//Ham goi email tong quat
	function sendEmail($header, $params)
	{	
		$this->Email->to = $header['to'];
		$this->Email->subject = $header['subject'];
		$this->Email->from = 'Admin '.'<'.Configure::read('smtp.username').'>';
		$this->Email->sendAs = 'both';
		$this->Email->template = $header['template'];
		$this->Email->smtpOptions = array(
			'port' => Configure::read('smtp.port'),
			'timeout' => '30',
			'host' => Configure::read('smtp.host'),
			'username' => Configure::read('smtp.username'),
			'password' => Configure::read('smtp.password')			
		);
		for($i=0, $n = sizeof($params); $i<$n; $i++)
		{
			$this->set("param$i", $params[$i]);
		}
		$this->Email->delivery = 'smtp';
		if ($this->Email->send()) {
			return true;
		} 
		else {
			CakeLog::write('debug error', "sendEmail: $$header \n $params" . $this->Email->smtpError);
		}
	}
	//goi mail yeu cau reset password
	function sendResetPasswordAlert($data)
	{
		$header = array('to' => $data['to'],
						'subject' => $data['subject'],
						'template' => $data['template']
						);
		$params = array($data['to'], $data['key']);
		$this->sendEmail($header, $params);
	}
	//goi mail thong bao password moi
	function sendNewPasswordAlert($data)
	{
		$header = array('to' => $data['to'],
						'subject' => $data['subject'],
						'template' => $data['template']
						);
		$params = array($data['newpw']);
		$this->sendEmail($header, $params);
	}
	//tien hanh reset password cho khach hang
	function resetpassword()
	{
		$msg = '';
		$this->layout = 'testcenter';
		$email = $_GET['m'];
		$key = $_GET['k'];
		$newpw = substr(sha1(mt_rand(10000,99999).time() . $email), 5, 10);
		$newhashedpw = md5($newpw);
		$this->Trainee->query('call resetpassword_prc(\'' . $email . '\',\'' . $key .  '\',\'' . $newhashedpw .'\', @result);');
		$resultset = $this->Trainee->query("SELECT @result");
		$result = $resultset[0][0]['@result'];
		if($result == 1)
		{
			$info = array(	'to' => $email,
							'subject' => $this->Util->getMessage('SUBJECT_EMAIL_NEWPW'),
							'template' => 'receive_password',
							'newpw' => $newpw
						);
			$this->sendNewPasswordAlert($info);
			$msg = 'Password has been changed!';
		}
		else
		{
			$msg = 'Change password failed!';
		}
		$this->set('msg', $msg);
		$this->set('result', $result);
	}
}
?>